package com.xxx.common.core.sampleframe.search;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Iterator;


public class QuerySearchArgumentsResolver implements HandlerMethodArgumentResolver  {

	@Override
	public boolean supportsParameter(MethodParameter parameter) { 
		return parameter.getParameterType().equals(QuerySearch.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		String objName = "search_";
		Object o = BeanUtils.instantiate(parameter.getParameterType());
		
		
		QuerySearch querySearch = (QuerySearch)o;
		Search search = new Search();
		StringBuffer key;
		String[] value;
		Field[] frr = parameter.getParameterType().getDeclaredFields();
		JSONObject kvObj = null ;
		for (Iterator<String> itr = webRequest.getParameterNames(); itr.hasNext();) {
			key = new StringBuffer(itr.next());
			if(key.toString().startsWith(objName)){
				value = webRequest.getParameterValues(key.toString());
				search.addSearchFilter(key.substring(objName.length(),key.length()), value[0]);
			}
			if(key.toString().startsWith("kv-")){
				value = webRequest.getParameterValues(key.toString());
				if(kvObj==null){
					kvObj = new JSONObject();
				}
				kvObj.put(key.substring("kv-".length(),key.length()), value);
			}
		}
		String page = webRequest.getParameter("page");
		if(StringUtils.isNotBlank(page)){
			search.addPageRequest(new PageRequest(Integer.valueOf(page),Integer.valueOf(webRequest.getParameter("size"))));
		}

		String distinct = webRequest.getParameter("distinct");
		if(StringUtils.isNotBlank(distinct )){
			search.jpaSelect(String.format("distinct %s ", distinct));
		}
		querySearch.setDistinct(distinct);
		querySearch.setSearch(search);
		querySearch.setFileName(webRequest.getParameter("fileName"));
		querySearch.setResponse(webRequest.getNativeResponse(HttpServletResponse.class));
		querySearch.setTitle(webRequest.getParameter("title"));
		querySearch.setFields(webRequest.getParameter("fields"));


		querySearch.setKvObj(kvObj);
		return o;
	}
	
	 
}